import java.util.Arrays;

/**
 * @projectName: java-daily-questions
 * @package: PACKAGE_NAME
 * @className: BubbleSort
 * @author: ZM
 * @description: 冒泡排序
 * @date: 2021/8/16 12:51
 * @version: 1.0
 */
public class BubbleSort {

    public static int[] sort(int[] arr) {
        int[] nums = new int[arr.length];
        System.arraycopy(arr, 0, nums, 0, arr.length);
        if (nums.length <= 1) {
            return nums;
        }

        boolean flag;
        for (int i = 0; i < nums.length; i++) {
            System.out.println("正在进行第" + (i+1) + "轮排序");
            //提前退出冒泡循环的标志位,即一次比较中没有交换任何元素，这个数组就已经是有序的了
            flag = false;
            for (int j = 0; j < nums.length - i - 1; j++) {
                if (nums[j] > nums[j + 1]) {
                    int temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                    flag = true;
                    System.out.printf("swap -> %d：%s\n", temp, Arrays.toString(nums));
                }
            }
            if (!flag){
                System.out.println("第" + i + "轮没有冒泡，排序结束");
                break;
            }
        }

        return nums;
    }

    public static void main(String[] args) {
        int[] arr = {10, 4, 2, 7, 5, 19, 11, 33, 28};
        System.out.printf("原数组: %s\n", Arrays.toString(arr));
        System.out.printf("排序后: %s\n", Arrays.toString(sort(arr)));

    }
}
